// 1.6 sisu认证(SisuAuthentication)
// 获取登陆重定向地址
use serde::{Deserialize, Serialize};

use crate::{api::{get_code_challange::CodeChallenge, get_device_token::get_device_token, get_random_state::get_random_state, get_signature::get_signature}, db::db_insert::db_insert};

// body 结构体
#[derive(Serialize, Deserialize, Debug)]
struct AuthBody {
    AppId: String,
    TitleId: String,
    RedirectUri: String,
    DeviceToken: String,
    Sandbox: String,
    TokenType: String,
    Offers: Vec<String>,
    Query: QueryParams,
}

#[derive(Serialize, Deserialize, Debug)]
struct QueryParams {
    display: String,
    code_challenge: String,
    code_challenge_method: String,
    state: String,
}

// response 结构体
#[derive(Deserialize, Debug)]
struct Response {
    MsaOauthRedirect: String,
    // 你可以加上 MsaRequestParameters 如果需要
}



use reqwest::Client;

pub async fn get_sisu_redirect_url() -> Result<String,Box<dyn std::error::Error>> {
    let body = AuthBody{
        AppId: "000000004c20a908".to_string(),
        TitleId: "328178078".to_string(),
        RedirectUri: "ms-xal-000000004c20a908://auth".to_string(),
        DeviceToken: get_device_token().await.unwrap(),
        Sandbox: "RETAIL".to_string(),
        TokenType: "code".to_string(),
        Offers: vec!["service::user.auth.xboxlive.com::MBI_SSL".to_string()],
        Query: QueryParams {
            display: "android_phone".to_string(),
            code_challenge: CodeChallenge::new().await.value,
            code_challenge_method: CodeChallenge::new().await.method,
            state: get_random_state(),
        }
    };
    let body = serde_json::to_string(&body).unwrap();
    // 签名
    let signature = get_signature("https://sisu.xboxlive.com/authenticate", "", &body);

    let client = Client::new();
    let response = client.post("https://sisu.xboxlive.com/authenticate")
        .header("x-xbl-contract-version", "1")
        .header("Cache-Control", "no-store, must-revalidate, no-cache")
        .header("Signature", signature)
        .body(body)
        .send().await?;
    
    let response_code :u16 = response.status().as_u16();
    let response_text = response.text().await?;

    println!("sisu response: {}", response_text);

    let mut  sisu_redirect__url = String::new();
    match response_code {
        200 => {
            let sisu_response:Response = serde_json::from_str(&response_text)?;
            sisu_redirect__url = sisu_response.MsaOauthRedirect;
            // let sisu_x_sessionid = sisu_response.headers.x_sessionid;
            println!("sisu_redirect_url: {}", sisu_redirect__url);
            db_insert("sisu_redirect_uri", &sisu_redirect__url).await.unwrap();
            // db_insert("sisu_x_sessionid", &sisu_x_sessionid).await.unwrap();
        },
        _ => {
            return Err(format!("sisu 请求失败，状态码: {}", response_code).into());
        }
    }

    return Ok(sisu_redirect__url);

}